package com.hhsj.dynamicui.server.servlet.user;


import com.hhsj.androidserver.HttpServlet;
import com.hhsj.androidserver.HttpServletRequest;
import com.hhsj.androidserver.HttpServletResponse;
import com.hhsj.androidserver.WebServlet;
import com.hhsj.dynamicui.model.AppBarBean;
import com.hhsj.dynamicui.model.GroupModel;
import com.hhsj.dynamicui.model.ModuleBean;
import com.hhsj.dynamicui.model.TitleViewBean;
import com.hhsj.dynamicui.model.UIModule;
import com.hhsj.dynamicui.model.ViewBean;
import com.hhsj.dynamicui.model.base.BaseModel;
import com.hhsj.dynamicui.server.DynamicUIService;
import com.hhsj.dynamicui.server.utils.ConstantUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询页面
 */
@WebServlet("/uhomecp-app/module.json")
public class ModuleServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse rep) throws Exception {
        this.doPost(req, rep);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse rep) throws Exception {
        System.out.println(HTTP_SERVLET + req.toString());
        System.out.println("\r\n");

        String page_position = null;
        if (req.getParameterValues("page_code") != null) {
            page_position = req.getParameterValues("page_code")[0];

        }
        if (page_position == null || "".equals(page_position)) {
            page_position = "tab_home";
        }

        UIModule uiModule = new UIModule();

        Connection connection = DynamicUIService.getInstance().getConnection();
        //1 查页面id
        String[] page = queryPage(connection, page_position);
        String pageId = page[0];
        String bodyCode = page[1];
        uiModule.setBodyCode(bodyCode);

        //2 通过页面id 查出 appbar
        queryAppbar(connection, pageId, uiModule);

        //3 查出floatbar
        queryFloatBar(connection, pageId, uiModule);

        //4 查出所有 组列表
        queryBody(connection, pageId, uiModule);

        //2.将数据封装到实体
        BaseModel<UIModule> baseModel = new BaseModel<>();
        baseModel.setData(uiModule);
        baseModel.setCode("0");
        baseModel.setMsg("成功");
        if (ConstantUtil.DEBUG) {
            System.out.println(HTTP_SERVLET + baseModel.toJSONString());
        }
        //3.返回响应
        rep.print(baseModel.toJSONString());
    }


    private AppBarBean queryAppbar(Connection connection, String pageId, UIModule uiModule) {
        // TODO: 2020/9/19
        return null;
    }


    /**
     * 查询悬浮按钮
     *
     * @param connection
     * @param pageId
     * @param uiModule
     */
    private void queryFloatBar(Connection connection, String pageId, UIModule uiModule) {
        // TODO: 2020/9/19
    }


    //查询并组装主干
    private void queryBody(Connection connection, String pageId, UIModule bodyBean) {

        //1，查询组id，和组标题id
        List<String> groupIds = new ArrayList<>();
        queryGroupIdList(connection, pageId, groupIds);

        //2，通过组id 查询 id
        List<GroupModel> groupModels = new ArrayList<>(groupIds.size());

        for (int i = 0, size = groupIds.size(); i < size; i++) {
            GroupModel model = queryGroup(connection, groupIds.get(i), pageId);
            groupModels.add(model);
        }
        bodyBean.setGroupList(groupModels);

        bodyBean.setProperty(queryViewBean(connection, pageId, ViewBean.TYPE_BODY, ViewBean.USE_TYPE_SELF));

    }

    /**
     * 组装组的详细信息
     *
     * @param connection
     * @param groupId
     * @param pageId
     * @return
     */
    private GroupModel queryGroup(Connection connection, String groupId, String pageId) {

        GroupModel groupModel = new GroupModel();

        //查询组视图属性
        ViewBean viewBean = queryViewBean(connection, groupId, ViewBean.TYPE_GROUP_LAYOUT, ViewBean.USE_TYPE_SELF);
        groupModel.setProperty(viewBean);

        //查询所有的业务
        List<ModuleBean> moduleBeans = new ArrayList<>();
        queryBusiness(connection, groupId, pageId, moduleBeans);
        groupModel.setBusinessModule(moduleBeans);

        //查询组标题
        TitleViewBean titleViewBean = queryGroupTitle(connection, groupId);
        groupModel.setTitleView(titleViewBean);

        return groupModel;
    }

    /**
     * 查询组标题
     *
     * @param connection
     * @param groupId
     * @return
     */
    private TitleViewBean queryGroupTitle(Connection connection, String groupId) {

        TitleViewBean titleViewBean = null;

        //查询数据
        String sql = String.format("select * from group_title_list where group_id=%s;", groupId);
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                titleViewBean = new TitleViewBean();
                String titleId = String.valueOf(resultSet.getInt("group_title_id"));
                String title_code = String.valueOf(resultSet.getString("title_code"));
                String title = resultSet.getString("title");
                String title1 = resultSet.getString("title1");
                String image = resultSet.getString("image");
                String image1 = resultSet.getString("image1");
                int support_more = resultSet.getInt("support_more");
                String more_action = resultSet.getString("more_action");

                titleViewBean.setTitleId(titleId);
                titleViewBean.setGroupId(groupId);
                titleViewBean.setTitleType(title_code);
                titleViewBean.setTitle(title);
                titleViewBean.setTitle1(title1);
                titleViewBean.setImage(image);
                titleViewBean.setImage1(image1);
                titleViewBean.setSupportMore(support_more);
                titleViewBean.setMoreAction(more_action);
                break;


            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (titleViewBean == null) {
            titleViewBean = new TitleViewBean();
        }

        //查询视图属性
        ViewBean viewBean = queryViewBean(connection, groupId, ViewBean.TYPE_GROUP_TITLE, ViewBean.USE_TYPE_SELF);
        titleViewBean.setProperty(viewBean);

        return titleViewBean;
    }

    /**
     * 查询当前组下面的所有业务模块
     *
     * @param connection
     * @param groupId
     * @param moduleBeans
     */
    private void queryBusiness(Connection connection, String groupId, String pageId, List<ModuleBean> moduleBeans) {
        //查询数据
        String sql = String.format("select widget_layout_id ,rank_no ,group_id,widget_code,widget_spec,business_code,business_params,child_widget_code,widget_desc from widget_list where group_id=%s and  page_id=%s order by rank_no;", groupId, pageId);
        System.out.println("sql:" + sql);

        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                String widget_id = String.valueOf(resultSet.getInt("widget_layout_id"));
                int rank = resultSet.getInt("rank_no");
                String group_id = String.valueOf(resultSet.getInt("group_id"));
                String widget_code = resultSet.getString("widget_code");
                String widget_spec = resultSet.getString("widget_spec");
                String business_code = resultSet.getString("business_code");
                String business_params = resultSet.getString("business_params");
                String child_widget_code = resultSet.getString("child_widget_code");
                String widget_desc = resultSet.getString("widget_desc");
                ModuleBean moduleBean = new ModuleBean();
                //描述
                moduleBean.setDesc(widget_desc);
                //排序
                moduleBean.setRankNo(rank);
                //组id
                moduleBean.setGroupId(group_id);

                //视图类型
                moduleBean.setWidgetCode(widget_code);
                moduleBean.setWidgetSpec(widget_spec);

                //业务类型
                moduleBean.setBusinessCode(business_code);
                moduleBean.setBusinessParams(business_params);

                //子视图类型
                moduleBean.setChildWidgetCode(child_widget_code);

                //视图参数
                ViewBean viewBean = queryViewBean(connection, widget_id, ViewBean.TYPE_WIDGET_LAYOUT, ViewBean.USE_TYPE_SELF);
                moduleBean.setProperty(viewBean);

                //子视图参数
                ViewBean itemViewBean = queryViewBean(connection, widget_id, ViewBean.TYPE_WIDGET_ITEM, ViewBean.USE_TYPE_CHILD);
                moduleBean.setChildProperty(itemViewBean);

                moduleBeans.add(moduleBean);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void queryGroupIdList(Connection connection, String pageId, List<String> groupIds) {

        //查询数据
        String sql = String.format("select (group_id) from group_list where page_id=\'%s\' order by rank_no;", pageId);
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                String groupId = String.valueOf(resultSet.getInt(1));
                groupIds.add(groupId);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //查询页面id OK
    private String[] queryPage(Connection connection, String page_position) {
        //查询数据
        String sql = String.format("select page_id,body_code from page_list where page_code =\'%s\' and page_status = 1;", page_position);

        System.out.println("sql:" + sql);

        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();

            while (resultSet.next()) {
                String id = String.valueOf(resultSet.getInt(1));
                String body_type = resultSet.getString(2);

                System.out.println("page_id = " + id + " body_code = " + body_type);
                return new String[]{id, body_type};
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param connection
     * @param owner_type
     * @param owner_id
     * @return
     * @see com.hhsj.dynamicui.model.ViewBean 的 TYPE
     */
    private ViewBean queryViewBean(Connection connection, String owner_id, String owner_type, String use_type) {
        //查询数据
        String sql = String.format("select * from view_property where owner_id=%s and owner_type=\'%s\' and use_type=\'%s\';",
                owner_id, owner_type, use_type);

        System.out.println("sql:" + sql);
        PreparedStatement statement = null;
        try {
            statement = connection.prepareStatement(sql);
            ResultSet resultSet = statement.executeQuery();


            while (resultSet.next()) {

                ViewBean viewBean = new ViewBean();
                ViewBean.Background background = new ViewBean.Background();
                ViewBean.Round round = new ViewBean.Round();
                ViewBean.WHSize whSize = new ViewBean.WHSize();
                ViewBean.Margin margin = new ViewBean.Margin();
                ViewBean.Padding padding = new ViewBean.Padding();
                viewBean.setBackground(background);
                viewBean.setRound(round);
                viewBean.setWhSize(whSize);
                viewBean.setMargin(margin);
                viewBean.setPadding(padding);

                String property_id = String.valueOf(resultSet.getInt(1));

                int background_type = resultSet.getInt(5);
                String background_color_str = resultSet.getString(6);
                String background_color_enum = resultSet.getString(7);

                int round_type = resultSet.getInt(8);
                int radius = resultSet.getInt(9);
                int top_left = resultSet.getInt(10);
                int top_right = resultSet.getInt(11);
                int bottom_left = resultSet.getInt(12);
                int bottom_right = resultSet.getInt(13);

                int wh_relation = resultSet.getInt(14);
                int width = resultSet.getInt(15);
                int height = resultSet.getInt(16);
                int r_width = resultSet.getInt(17);
                int r_height = resultSet.getInt(18);


                int margin_left = resultSet.getInt(19);
                int margin_top = resultSet.getInt(20);
                int margin_right = resultSet.getInt(21);
                int margin_bottom = resultSet.getInt(22);

                int padding_left = resultSet.getInt(23);
                int padding_top = resultSet.getInt(24);
                int padding_right = resultSet.getInt(25);
                int padding_bottom = resultSet.getInt(26);

                viewBean.setPropertyId(property_id);

                background.setBackgroundType(background_type);
                background.setBackgroundColorStr(background_color_str);
                background.setBackgroundColorEnum(background_color_enum);

                round.setRoundType(round_type);
                round.setRadius(radius);
                round.setCornerTopLeft(top_left);
                round.setCornerTopRight(top_right);
                round.setCornerBottomLeft(bottom_left);
                round.setCornerBottomRight(bottom_right);

                whSize.setWhRelation(wh_relation);
                whSize.setWidth(width);
                whSize.setHeight(height);
                whSize.setRWidth(r_width);
                whSize.setRHeight(r_height);


                margin.setMarginLeft(margin_left);
                margin.setMarginTop(margin_top);
                margin.setMarginRight(margin_right);
                margin.setMarginBottom(margin_bottom);

                padding.setPaddingLeft(padding_left);
                padding.setPaddingTop(padding_top);
                padding.setPaddingRight(padding_right);
                padding.setPaddingBottom(padding_bottom);

                return viewBean;

            }


        } catch (SQLException e) {
            e.printStackTrace();
        }

        return null;
    }

}